package china.accountinghelper.business;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.xdroid.base.BusinessBase;

import china.wc.tallyhelper.database.SQLiteDALModelBook;
import china.wc.tallyhelper.model.ModelBook;
import china.wc.tallyhelper.model.ModelExpense;
import china.wc.tallyhelper.model.ModelExpenseDetail;
import china.wc.tallyhelper.model.ModelPerson;
import china.wc.tallyhelper.model.ModelStatistics;

/**
 * 本类是所有业务类的父类，封装和ModelBook实体类相关的业务逻辑。
 * 本类的作用是将DAL层的方法进一步封装，并将其返回结果进行必要的处理，方便Activity、Adapter进行调用。
 * 
 * @author 王超
 * 
 */
public class BusinessBook extends BusinessBase<ModelBook>
{
    private BusinessPerson mBusinessPerson = new BusinessPerson();
    private BusinessExpense mBusinessExpense = new BusinessExpense();
    private BusinessExpenseDetail mBusinessExpenseDetail = new BusinessExpenseDetail();
    
    public BusinessBook()
    {
        super(new SQLiteDALModelBook(ModelBook.class));
    }

    /**
     * 返回所有ModelBook对象，State值大的在前。
     * 
     * @return 包含所有实体类对象的List
     */
    @Override
    public List<ModelBook> select()
    {
        String _StateColumsName = getSQLiteDAL().getFieldColumnMap().get("mState");
        
        return getSQLiteDAL().select(null, null, null, null, _StateColumsName + " DESC");
    }
    
    /**
     * 返回所有State不等于ModelBook.STATE_DISABLED的账本，State值大的在前。
     * 
     * @return
     */
    public List<ModelBook> selectEnabledBook()
    {
        String _StateColumsName = getSQLiteDAL().getFieldColumnMap().get("mState");
        
        return getSQLiteDAL().select(_StateColumsName+"!="+ModelBook.STATE_DISABLED, null, null, null, _StateColumsName + " DESC");
    }
    
    /**
     * 返回默认账本
     * 
     * @return 默认账本，若没有默认账本，则返回null。
     */
    public ModelBook selectDefaultBook()
    {
        String _StateColumsName = getSQLiteDAL().getFieldColumnMap().get("mState");
        List<ModelBook> _ListModelBook = getSQLiteDAL().select(_StateColumsName+"="+ModelBook.STATE_DEFAULT, null, null, null, null);
        
        if (_ListModelBook.size()<=0) {
            return null;
        } else {
            return _ListModelBook.get(0);
        }
    }

    /**
     * 将ModelBook对象插入数据库。
     * 插入时，判断ModelBook对象的STATE，若等于ModelBook.STATE_DEFAULT，则设置为默认账本。
     * 
     */
    @Override
    public boolean insertModel(ModelBook pBook)
    {
        boolean _Result = false;
        
        getSQLiteDAL().beginTransaction();
        try {
            if (pBook.getState() == ModelBook.STATE_DEFAULT) {
                if (setAllStateEnabled() && super.insertModel(pBook)) {
                    _Result = true;
                    getSQLiteDAL().setTransactionSuccessful();
                }
            } else {
                if (super.insertModel(pBook)) {
                    _Result = true;
                    getSQLiteDAL().setTransactionSuccessful();
                }
            }
        } finally {
            getSQLiteDAL().endTransaction();
        }

        return _Result;
    }

    /**
     * 更新ModelBook对象对应的记录。
     * 更新时，判断ModelBook对象的STATE，若等于ModelBook.STATE_DEFAULT，则设置为默认账本。
     */
    @Override
    public boolean updateModel(ModelBook pBook)
    {
        boolean _Result = false;

        getSQLiteDAL().beginTransaction();
        try {
            if (pBook.getState() == ModelBook.STATE_DEFAULT) {
                if (setAllStateEnabled() && super.updateModel(pBook)) {
                    _Result = true;
                    getSQLiteDAL().setTransactionSuccessful();
                }
            } else {
                if ( super.updateModel(pBook) ) {
                    _Result = true;
                    getSQLiteDAL().setTransactionSuccessful();
                }
            }
        } finally {
            getSQLiteDAL().endTransaction();
        }

        return _Result;
    }

    /**
     * 启用账本
     * 
     * @param pID
     *            账本ID
     * @return 启用成功返回true，失败返回false。
     */
    public boolean enableBook(long pID)
    {
        ModelBook _ModelBook = select(pID);

        return enableBook(_ModelBook);
    }

    /**
     * 启用账本
     * 
     * @param pBook
     *            ModelBook对象
     * @return 启用成功返回true，失败返回false。
     */
    public boolean enableBook(ModelBook pBook)
    {
        pBook.setState(ModelBook.STATE_ENABLED);

        return updateModel(pBook);
    }

    /**
     * 设置默认账本
     * 
     * @param pID
     *            账本ID
     * @return 启用成功返回true，失败返回false。
     */
    public boolean setDefaultBook(long pID)
    {
        ModelBook _ModelBook = select(pID);
        return setDefaultBook(_ModelBook);
    }

    /**
     * 设置默认账本
     * 
     * @param pBook
     *            ModelBook对象
     * @return 启用成功返回true，失败返回false。
     */
    public boolean setDefaultBook(ModelBook pBook)
    {
        pBook.setState(ModelBook.STATE_DEFAULT);

        return updateModel(pBook);
    }

    /**
     * 禁用账本
     * 
     * @param pID
     *            账本ID
     * @return 禁用成功返回true，失败返回false。
     */
    public boolean disableBook(long pID)
    {
        ModelBook _ModelBook = select(pID);
        return disableBook(_ModelBook);
    }

    /**
     * 禁用账本
     * 
     * @param pBook
     *            ModelBook对象
     * @return 禁用成功返回true，失败返回false。
     */
    public boolean disableBook(ModelBook pBook)
    {
        pBook.setState(ModelPerson.STATE_DISABLED);
        return updateModel(pBook);
    }
    
    public List<ModelStatistics> statistics(ModelBook pBook)
    {
        List<ModelStatistics> _StatisticsList = new ArrayList<ModelStatistics>();
        
        List<ModelExpense> _ExpensesList = mBusinessExpense.select(pBook);
        for (ModelExpense _TemExpense : _ExpensesList) {
            List<ModelExpenseDetail> _ExpenseDetailsList = mBusinessExpenseDetail.select(_TemExpense);
            for (ModelExpenseDetail _TemExpenseDetail : _ExpenseDetailsList) {
                
                ModelStatistics _Statistics = new ModelStatistics();
                _Statistics.setPayer(mBusinessPerson.select(_TemExpense.getPayerID()));
                _Statistics.setConsumer(mBusinessPerson.select(_TemExpenseDetail.getConsumerID()));
                _Statistics.setMoney(_TemExpenseDetail.getMoney1());
                
                if (_StatisticsList.contains(_Statistics)) {
                    ModelStatistics _Tem = _StatisticsList.get(_StatisticsList.indexOf(_Statistics));
                    if (_Tem.getPayer().equals(_Statistics.getPayer()) && _Tem.getConsumer().equals(_Statistics.getConsumer())) {
                        _Tem.setMoney(_Tem.getMoney1()+_Statistics.getMoney1());
                    } else {
                        _Tem.setMoney(_Tem.getMoney1()-_Statistics.getMoney1());
                    }
                } else {
                    _StatisticsList.add(_Statistics);
                }
                
            }
        }
        
        for (ModelStatistics _TemStatistics : _StatisticsList) {
            if (_TemStatistics.getMoney1()<0) {
                ModelPerson _Payer = _TemStatistics.getConsumer();
                ModelPerson _Consumer = _TemStatistics.getPayer();
                _TemStatistics.setPayer(_Payer);
                _TemStatistics.setConsumer(_Consumer);
                _TemStatistics.setMoney(Math.abs(_TemStatistics.getMoney1()));
            } else if (_TemStatistics.getPayer().equals(_TemStatistics.getConsumer())) {
                _StatisticsList.remove(_TemStatistics);
            }
        }
        
        Collections.sort(_StatisticsList);
        
        return _StatisticsList;
    }
    
    /**
     * 将原来的ModelBook.STATE_DEFAULT状态的账本，设置为ModelBook.STATE_ENABLED状态。设置新的默认账本前，要调用本方法，避免出现2个默认账本。
     * 
     * @return 设置成功返回true，设置失败返回false。
     */
    private boolean setAllStateEnabled()
    {
        return getSQLiteDAL().execSQL("UPDATE Book SET State = " + ModelBook.STATE_ENABLED + " WHERE State == " + ModelBook.STATE_DEFAULT);
    }

}
